package datasource

import (
	"alarm-flow/config"
	"fmt"
	_ "github.com/lib/pq"
	"time"
	"xorm.io/xorm"
	"xorm.io/xorm/names"
)

var PgEngine *xorm.Engine

func InitPg(config config.PG) (err error) {
	connStr, err := config.ConnStr()
	if err != nil {
		return
	}

	PgEngine, err = xorm.NewEngine("postgres", connStr)
	if err != nil {
		err = fmt.Errorf("connect postgres error:%v", err)
		return
	}

	PgEngine.SetMaxIdleConns(10)
	PgEngine.SetMaxOpenConns(100)
	PgEngine.SetConnMaxLifetime(time.Hour)
	PgEngine.SetConnMaxIdleTime(time.Hour)
	PgEngine.SetMapper(names.GonicMapper{})
	PgEngine.ShowSQL(config.ShowSQL)

	return PgEngine.Ping()
}
